package com.dream.service.recommender.splitter.strage.impl;

import com.dream.service.recommender.domain.splitter.DefaultConfig;
import com.dream.service.recommender.domain.splitter.ExpConfig;
import com.dream.service.recommender.domain.splitter.PlacementConfig;
import com.dream.service.recommender.domain.splitter.SplitterRequest;
import com.dream.service.recommender.splitter.strage.Strategy;
import com.dream.service.recommender.toolkits.utils.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhiji on 2016/3/15.
 */
public abstract class BaseStrategy implements Strategy {

    /**
     * 流量最大值
     */
    protected final int maxtraffic = 100;

    /**
     * 获取流量的详细切分
     * @param placementConfig
     * @return
     */
    protected Map<Integer, ExpConfig> buildTrafficMap(PlacementConfig placementConfig) {
        if (placementConfig == null) {
            return null;
        }
        Map<Integer, ExpConfig> expConfigMap = new HashMap<Integer, ExpConfig>();
        List<ExpConfig> expConfigList = placementConfig.getExp_config_list();
        int curtraffic = 0;
        for (ExpConfig expConfig : expConfigList) {
            int traffic = expConfig.getTraffic();
            int maxtraffic = curtraffic + traffic;
            for (int i = curtraffic; i < maxtraffic && i < maxtraffic; i++, curtraffic++) {
                expConfigMap.put(i, expConfig);
            }
        }
        return expConfigMap;
    }

    /**
     * 根据seed值获取配置信息
     * @param seed
     * @param placementConfig
     * @param defaultConfig
     * @return
     */
    protected ExpConfig getExpConfigBySeed(int seed, PlacementConfig placementConfig, ExpConfig defaultConfig) {
        Map<Integer, ExpConfig> expConfigMap = buildTrafficMap(placementConfig);
        ExpConfig expConfig = expConfigMap.get(seed);
        return expConfig == null ? defaultConfig : expConfig;
    }

    /**
     * 获取当前的实验配置
     * @param placeConfig
     * @param splitterRequest
     * @return
     */
    @Override
    public ExpConfig getCurrentExpConfig(PlacementConfig placeConfig, SplitterRequest splitterRequest) {
        if (placeConfig == null) {
            return null;
        }
        List<ExpConfig> expConfigList = placeConfig.getExp_config_list();
        DefaultConfig defaultConfig = placeConfig.getDefault_config();
        if (splitterRequest == null || StringUtils.isEmpty(expConfigList)) {
            return defaultConfig;
        }
        int seed = getSeed(splitterRequest);
        return getExpConfigBySeed(seed, placeConfig, defaultConfig);
    }

    /**
     * 获取分流的seed值
     * @param splitterRequest
     * @return
     */
    public abstract int getSeed(SplitterRequest splitterRequest);

}
